package main

import (
	"fmt"
	"math/rand"
	"time"

	"github.com/alicebob/miniredis/v2"
)

func main() {
	rand.Seed(time.Now().UnixNano())

	// 使用原生实现
	fmt.Println("=== Native Implementation ===")
	testLeaderboard(NewLeaderboard())

	// 创建内存Redis服务器
	mr, err := miniredis.Run()
	if err != nil {
		panic(err)
	}
	defer mr.Close()

	// 使用内存Redis实现
	fmt.Println("\n=== In-Memory Redis Implementation ===")
	redisLB := NewRedisLeaderboard(mr.Addr())
	testLeaderboard(redisLB)

	// 使用内存Redis密集排名实现
	fmt.Println("\n=== In-Memory Redis Dense Ranking ===")
	denseLB := NewRedisDenseLeaderboard(mr.Addr())
	testLeaderboard(denseLB)
}

func testLeaderboard(lb LeaderboardService) {
	// 模拟100个玩家
	playerIDs := make([]string, 100)
	for i := 0; i < 100; i++ {
		playerIDs[i] = fmt.Sprintf("player%d", i+1)
	}

	// 随机更新分数
	for i := 0; i < 1000; i++ {
		playerID := playerIDs[rand.Intn(len(playerIDs))]
		score := rand.Intn(1000)
		lb.UpdateScore(playerID, score)
	}

	// 测试功能
	fmt.Println("=== Top 10 Players ===")
	top10 := lb.GetTopN(10)
	for _, rank := range top10 {
		fmt.Printf("Rank %d: %s (Score: %d)\n", rank.Rank, rank.PlayerID, rank.Score)
	}

	fmt.Println("\n=== Player50's Rank ===")
	if rank, ok := lb.GetPlayerRank("player50"); ok {
		fmt.Printf("Player50 is rank %d with score %d\n", rank.Rank, rank.Score)
	} else {
		fmt.Println("Player50 not found")
	}

	fmt.Println("\n=== Player50's Neighbors ===")
	neighbors := lb.GetPlayerRankRange("player50", 2)
	for _, rank := range neighbors {
		fmt.Printf("Rank %d: %s (Score: %d)\n", rank.Rank, rank.PlayerID, rank.Score)
	}
}

type LeaderboardService interface {
	UpdateScore(playerID string, score int)
	GetPlayerRank(playerID string) (RankInfo, bool)
	GetTopN(n int) []RankInfo
	GetPlayerRankRange(playerID string, rangeSize int) []RankInfo
}
